package com.lishangshan.oas_system.controller.mail;

import com.lishangshan.oas_system.model.dao.maildao.InMailDao;
import com.lishangshan.oas_system.model.dao.maildao.MailnumberDao;
import com.lishangshan.oas_system.model.dao.maildao.MailreciverDao;
import com.lishangshan.oas_system.model.dao.system.StatusDao;
import com.lishangshan.oas_system.model.dao.system.TypeDao;
import com.lishangshan.oas_system.model.dao.user.UserDao;
import com.lishangshan.oas_system.model.entity.mail.Inmaillist;
import com.lishangshan.oas_system.model.entity.mail.Mailreciver;
import com.lishangshan.oas_system.model.entity.mail.Pagemail;
import com.lishangshan.oas_system.model.entity.user.User;
import com.lishangshan.oas_system.service.mail.MailServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/")
public class MailController2 {
    @Autowired
    private MailreciverDao mailreciverDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private InMailDao inMailDao;
    @Autowired
    private MailServices mailServices;
    @Autowired
    private StatusDao statusDao;
    @Autowired
    private TypeDao typeDao;
    @Autowired
    private MailnumberDao mailnumberDao;
    @Autowired
    private MailControllerFun mailControllerFun;
    @Autowired
    private MailServices mservice;

    /**
     * 删除邮件
     */
    @RequestMapping("alldelete")
    public String delete(HttpServletRequest req, @SessionAttribute("userId") Long userId, Model model,
                         @RequestParam(value = "page", defaultValue = "0") int page,
                         @RequestParam(value = "size", defaultValue = "5") int size) {
        //查找用户
        User user = userDao.findOne(userId);
        String title = req.getParameter("title");
        Page<Pagemail> pagelist = null;
        Page<Inmaillist> pagemail = null;
        List<Map<String, Object>> maillist = null;
        //得到删除id
        String ids = req.getParameter("ids");
        if (("收件箱").equals(title)) {
            StringTokenizer st = new StringTokenizer(ids, ",");
            while (st.hasMoreElements()) {
                //找到该用户联系邮件的中间记录
                Mailreciver mailr = mailreciverDao.findbyReciverIdAndmailId(user, Long.parseLong(st.nextToken()));
                if (!Objects.isNull(mailr)) {
                    //把删除的字段改为1
                    mailr.setDel(true);
                    mailreciverDao.save(mailr);
                } else {
                    return "redirect:/notlimit";
                }
            }
            //分页及查找
            pagelist = mservice.recive(page, size, user, null, title);
            maillist = mservice.mail(pagelist);
        } else if (("发件箱").equals(title)) {
            StringTokenizer st = new StringTokenizer(ids, ",");
            while (st.hasMoreElements()) {
                //找到该邮件
                Inmaillist inmail = inMailDao.findByMailUseridAndMailId(user, Long.parseLong(st.nextToken()));
                if (!Objects.isNull(inmail)) {
                    //把删除的字段改为1
                    inmail.setDel(true);
                    inMailDao.save(inmail);
                } else {
                    return "redirect:/notlimit";
                }
            }
            pagemail = mservice.inmail(page, size, user, null, title);
            maillist = mservice.maillist(pagemail);
        } else if (("草稿箱").equals(title)) {
            StringTokenizer st = new StringTokenizer(ids, ",");
            while (st.hasMoreElements()) {
                //找到该邮件
                Inmaillist inmail = inMailDao.findByMailUseridAndMailId(user, Long.parseLong(st.nextToken()));
                if (!Objects.isNull(inmail)) {
                    inMailDao.delete(inmail);
                } else {
                    return "redirect:/notlimit";
                }
            }
            pagemail = mservice.inmail(page, size, user, null, title);
            maillist = mservice.maillist(pagemail);
        } else {
            //垃圾箱
            StringTokenizer st = new StringTokenizer(ids, ",");
            while (st.hasMoreElements()) {
                Long mailid = Long.parseLong(st.nextToken());
                //查看中间表关于这条邮件的del字段
                List<Boolean> dellist = mailreciverDao.findbyMailId(mailid);

                //判断中间表中关于这条邮件是否还有del字段为false的
                if (dellist.contains(false)) {
                    Mailreciver mailr = mailreciverDao.findbyReciverIdAndmailId(user, mailid);
                    if (!Objects.isNull(mailr)) {
                        mailreciverDao.delete(mailr);
                    } else {
                        return "redirect:/notlimit";
                    }
                } else {
                    Inmaillist imail = inMailDao.findOne(mailid);
                    //判断这条邮件的del字段是为true
                    if (imail.getDel().equals(true)) {
                        List<Mailreciver> mreciver = mailreciverDao.findByMailId(mailid);
                        //循环删除关于这条邮件的所有中间表信息
                        for (Mailreciver mailreciver : mreciver) {
                            mailreciverDao.delete(mailreciver);
                        }
                        inMailDao.delete(imail);
                    } else {
                        //这条邮件的del字段为false，则删除中间表信息
                        Mailreciver mailr = mailreciverDao.findbyReciverIdAndmailId(user, mailid);
                        if (!Objects.isNull(mailr)) {
                            mailreciverDao.delete(mailr);
                        } else {
                            return "redirect:/notlimit";
                        }
                    }
                }
            }
            pagelist = mservice.recive(page, size, user, null, title);
            maillist = mservice.mail(pagelist);
        }
        if (!Objects.isNull(pagelist)) {
            model.addAttribute("page", pagelist);
        } else {
            model.addAttribute("page", pagemail);
        }
        model.addAttribute("maillist", maillist);
        model.addAttribute("url", "mailtitle");
        model.addAttribute("mess", title);
        model.addAttribute("sort", "&title=" + title);
        return "mail/mailbody";
    }

    /**
     * 标记已读
     */
    @RequestMapping("watch")
    public String watch(@SessionAttribute("userId") Long userId, Model model, HttpServletRequest req,
                        @RequestParam(value = "page", defaultValue = "0") int page,
                        @RequestParam(value = "size", defaultValue = "5") int size) {
        User user = userDao.findOne(userId);
        String title = req.getParameter("title");
        String ids = req.getParameter("ids");
        Page<Pagemail> pagelist = null;
        List<Map<String, Object>> maillist = null;

        if (("收件箱").equals(title)) {
            StringTokenizer st = new StringTokenizer(ids, ",");
            while (st.hasMoreElements()) {
                //找到该用户联系邮件的中间记录
                Mailreciver mailr = mailreciverDao.findbyReciverIdAndmailId(user, Long.parseLong(st.nextToken()));
                if (mailr.getRead().equals(false)) {

                    mailr.setRead(true);
                } else {

                    mailr.setRead(false);
                }

                mailreciverDao.save(mailr);
            }
            //分页及查找
            pagelist = mservice.recive(page, size, user, null, title);

        } else {
            //垃圾箱
            StringTokenizer st = new StringTokenizer(ids, ",");
            while (st.hasMoreElements()) {
                //找到该用户联系邮件的中间记录
                Mailreciver mailr = mailreciverDao.findbyReciverIdAndmailId(user, Long.parseLong(st.nextToken()));
                if (mailr.getRead().equals(false)) {
                    mailr.setRead(true);
                } else {
                    mailr.setRead(false);
                }
                mailreciverDao.save(mailr);
            }
            //分页及查找
            pagelist = mservice.recive(page, size, user, null, title);
        }
        maillist = mservice.mail(pagelist);

        model.addAttribute("page", pagelist);
        model.addAttribute("maillist", maillist);
        model.addAttribute("url", "mailtitle");
        model.addAttribute("mess", title);
        return "mail/mailbody";
    }

    /**
     * 批量标星
     */
    @RequestMapping("star")
    public String star(@SessionAttribute("userId") Long userId, Model model, HttpServletRequest req,
                       @RequestParam(value = "page", defaultValue = "0") int page,
                       @RequestParam(value = "size", defaultValue = "5") int size) {
        User user = userDao.findOne(userId);
        String title = req.getParameter("title");
        String ids = req.getParameter("ids");
        Page<Pagemail> pagelist = null;
        Page<Inmaillist> pagemail = null;
        List<Map<String, Object>> maillist = null;

        if (("收件箱").equals(title)) {
            StringTokenizer st = new StringTokenizer(ids, ",");
            while (st.hasMoreElements()) {

                //找到该用户联系邮件的中间记录
                Mailreciver mailr = mailreciverDao.findbyReciverIdAndmailId(user, Long.parseLong(st.nextToken()));
                if (mailr.getStar().equals(false)) {
                    mailr.setStar(true);
                } else {
                    mailr.setStar(false);
                }
                mailreciverDao.save(mailr);
            }
            //分页及查找
            pagelist = mservice.recive(page, size, user, null, title);
            maillist = mservice.mail(pagelist);
        } else if (("发件箱").equals(title)) {
            StringTokenizer st = new StringTokenizer(ids, ",");
            while (st.hasMoreElements()) {
                //找到该邮件
                Inmaillist inmail = inMailDao.findByMailUseridAndMailId(user, Long.parseLong(st.nextToken()));
                if (inmail.getStar().equals(false)) {
                    inmail.setStar(true);
                } else {
                    inmail.setStar(false);
                }
                inMailDao.save(inmail);
            }
            pagemail = mservice.inmail(page, size, user, null, title);
            maillist = mservice.maillist(pagemail);
        } else if (("草稿箱").equals(title)) {
            StringTokenizer st = new StringTokenizer(ids, ",");
            while (st.hasMoreElements()) {
                //找到该邮件
                Inmaillist inmail = inMailDao.findByMailUseridAndMailId(user, Long.parseLong(st.nextToken()));
                if (inmail.getStar().equals(false)) {
                    inmail.setStar(true);
                } else {
                    inmail.setStar(false);
                }
                inMailDao.save(inmail);
            }
            pagemail = mservice.inmail(page, size, user, null, title);
            maillist = mservice.maillist(pagemail);
        } else {
            //垃圾箱
            StringTokenizer st = new StringTokenizer(ids, ",");
            while (st.hasMoreElements()) {
                //找到该用户联系邮件的中间记录
                Mailreciver mailr = mailreciverDao.findbyReciverIdAndmailId(user, Long.parseLong(st.nextToken()));
                if (mailr.getStar().equals(false)) {
                    mailr.setStar(true);
                } else {
                    mailr.setStar(false);
                }
                mailreciverDao.save(mailr);
            }
            //分页及查找
            pagelist = mservice.recive(page, size, user, null, title);
            maillist = mservice.mail(pagelist);
        }

        if (!Objects.isNull(pagelist)) {
            model.addAttribute("page", pagelist);
        } else {
            model.addAttribute("page", pagemail);
        }
        model.addAttribute("maillist", maillist);
        model.addAttribute("url", "mailtitle");
        model.addAttribute("mess", title);
        return "mail/mailbody";
    }

    /**
     * 批量恢复
     *
     * @param user
     * @param ids
     * @param title
     * @param model
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/refresh")
    public String refresh(@SessionAttribute("userId") Long userId,
                          @RequestParam("ids") Long[] ids,
                          @RequestParam("title") String title, Model model,
                          @RequestParam(value = "page", defaultValue = "0") Integer page,
                          @RequestParam(value = "size", defaultValue = "5") Integer size) {
        User user = userDao.findOne(userId);
        for (Long id : ids) {
            Mailreciver mailr = mailreciverDao.findbyReciverIdAndmailId(user, id);
            if (mailr != null) {
                //把恢复的字段改为0
                mailr.setDel(false);
                mailreciverDao.save(mailr);
            } else {
                return "redirect:/notlimit";
            }
        }
        //分页及查找
        Page<Pagemail> pagelist = mservice.recive(page, size, user, null, title);

        List<Map<String, Object>> maillist = mservice.mail(pagelist);

//        Page<Inmaillist> pagemail = mservice.inmail(page, size, user, null, title);

        if (!Objects.isNull(pagelist)) {
            model.addAttribute("page", pagelist);
        } else {
//            model.addAttribute("page", pagemail);
        }
        model.addAttribute("maillist", maillist);
        model.addAttribute("url", "mailtitle");
        model.addAttribute("mess", title);
        return "mail/mailbody";
    }

    /**
     * 异步刷新界面
     *
     * @param request
     * @return
     */
    @RequestMapping("getNum")
    @ResponseBody
    public Map model(HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<>();
        User user = (User) request.getSession().getAttribute("user");
        List<Mailreciver> noreadlist = mailreciverDao.findByReadAndDelAndReciverId(false, false, user);
        //查找创建了但是却没有发送的邮件
        List<Inmaillist> nopushlist = inMailDao.findByPushAndDelAndMailUserid(false, false, user);
        //查找发件条数
        List<Inmaillist> pushlist = inMailDao.findByPushAndDelAndMailUserid(true, false, user);
        //查找收件箱删除的邮件条数
        List<Mailreciver> rubbish = mailreciverDao.findByDelAndReciverId(true, user);
        map.put("noread", noreadlist.size());
        map.put("push", nopushlist.size());
        map.put("nopush", pushlist.size());
        map.put("rubbish", rubbish.size());
        System.out.println(rubbish.size());
        return map;
    }

}
